import sha
from time import time
from django import forms
from django.contrib.contenttypes.models import ContentType
from django.core.exceptions import ObjectDoesNotExist
from models import SimpleComment


class InlineContentTypeField(forms.ModelChoiceField):
    def __init__(self, *args, **kwargs):
        kwargs['widget'] = kwargs.pop('widget', forms.widgets.TextInput)
        super(InlineContentTypeField, self).__init__(*args, **kwargs)
        
    def clean(self, value):
        if not value and not self.required:
            return None
        try:
            #return self.queryset.filter(name=value).get()
            return ContentType.objects.get(pk=value)
        except self.queryset.model.DoesNotExist:
            raise forms.ValidationError("No match for %s." % (value,))

class SubmitComment(forms.ModelForm):
    def __init__(self, POST = '', model='', request='', *args, **kwargs):
        if POST:
            super(SubmitComment, self).__init__(POST, *args, **kwargs)
        else:
            super(SubmitComment, self).__init__(*args, **kwargs)
        
        if model and request:
            if not self.data.get('next'):
                self.initial['next'] = str(request.get_full_path())
            if not self.data.get('content_type'):
                self.initial['content_type'] = str(ContentType.objects.get_for_model(model).id)
            if not self.data.get('timestamp'):
                self.initial['timestamp'] = str(time())
            if not self.data.get('object_id'):
                self.initial['object_id'] = str(model.id)
            if not self.data.get('author_ipaddress'):
                self.initial['author_ipaddress'] = str(request.META['REMOTE_ADDR'])

            # Digital signature for this request
            if not self.data.get('signature'):
                self.initial['signature'] = sha.new(
                    self.initial['timestamp']+
                    self.initial['next']+
                    self.initial['author_ipaddress']
                ).hexdigest()
    
    content_type = InlineContentTypeField(queryset=ContentType.objects.all(), widget=forms.HiddenInput)
    object_id = forms.IntegerField(widget=forms.HiddenInput)
    next = forms.CharField(widget=forms.HiddenInput)
    signature = forms.CharField(widget=forms.HiddenInput)
    timestamp = forms.CharField(widget=forms.HiddenInput)
    
    class Meta:
        model = SimpleComment
        exclude = ('author_ipaddress', 'submit_date',)
    
    def is_potential_spam(self, request):
        # is_valid should be called first
        if not self.is_valid():
            return True
        request_signature = sha.new(
            self.cleaned_data['timestamp']+
            self.cleaned_data['next']+
            str(request.META['REMOTE_ADDR'])
            ).hexdigest()
            
        if request_signature != self.cleaned_data['signature']:
            assert False
            return True
        
        if float(time()) - float(self.cleaned_data['timestamp']) < 10:
            return True
        
        return False
            